<template>
  <div class="playing-appointment-container">
    <div class="page-header">
      <h2>约球活动</h2>
      <p>寻找球友，组织活动，一起享受羽毛球的乐趣</p>
    </div>

    <div class="appointment-content">
      <!-- 创建约球活动按钮 -->
      <div class="create-appointment-btn-container">
        <button class="create-appointment-btn" @click="openCreateModal">
          <i class="plus-icon">+</i> 创建约球活动
        </button>
      </div>

      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <div class="search-box">
          <input type="text" v-model="searchKeyword" placeholder="搜索场地或发起人..." @input="filterAppointments">
        </div>
        <div class="filter-options">
          <select v-model="selectedDate" @change="filterAppointments">
            <option value="all">全部日期</option>
            <option value="today">今天</option>
            <option value="tomorrow">明天</option>
            <option value="weekend">本周末</option>
            <option value="nextWeek">下周</option>
          </select>
          <select v-model="selectedLocation" @change="filterAppointments">
            <option value="all">全部场地</option>
            <option value="indoor">室内场地</option>
            <option value="outdoor">室外场地</option>
          </select>
        </div>
      </div>

      <!-- 约球活动列表 -->
      <div class="appointments-list">
        <div class="appointment-card" v-for="appointment in filteredAppointments" :key="appointment.id">
          <div class="appointment-header">
            <div class="appointment-title">
              <h3>{{ appointment.title }}</h3>
              <span class="organizer">发起人: {{ appointment.organizer }}</span>
            </div>
            <div class="appointment-status" :class="getStatusClass(appointment)">
              {{ getStatusText(appointment) }}
            </div>
          </div>

          <div class="appointment-details">
            <div class="detail-item">
              <i class="icon">📅</i>
              <span>{{ formatDate(appointment.date) }} {{ appointment.time }}</span>
            </div>
            <div class="detail-item">
              <i class="icon">📍</i>
              <span>{{ appointment.location }} ({{ appointment.locationType }})</span>
            </div>
            <div class="detail-item">
              <i class="icon">👥</i>
              <span>{{ appointment.currentPlayers }}/{{ appointment.maxPlayers }} 人</span>
            </div>
            <div class="detail-item">
              <i class="icon">💬</i>
              <span>{{ appointment.description }}</span>
            </div>
          </div>

          <div class="appointment-actions">
            <button class="join-btn" @click="joinAppointment(appointment)" :disabled="!canJoin(appointment)">
              {{ canJoin(appointment) ? '加入活动' : getJoinButtonText(appointment) }}
            </button>
            <button class="share-btn">分享</button>
          </div>
        </div>
      </div>

      <div class="no-appointments" v-if="filteredAppointments.length === 0">
        暂无约球活动，创建一个新活动吧！
      </div>
    </div>

    <!-- 创建约球活动模态框 -->
    <div class="modal-overlay" :class="{ active: createModalOpen }" @click="closeCreateModal"></div>
    <div class="modal" :class="{ active: createModalOpen }">
      <div class="modal-header">
        <h3>创建约球活动</h3>
        <button class="close-modal" @click="closeCreateModal">×</button>
      </div>
      <div class="modal-body">
        <form @submit.prevent="submitAppointment">
          <div class="form-group">
            <label for="title">活动标题</label>
            <input type="text" id="title" v-model="newAppointment.title" required placeholder="输入活动标题">
          </div>

          <div class="form-group">
            <label for="date">活动日期</label>
            <input type="date" id="date" v-model="newAppointment.date" required>
          </div>

          <div class="form-group">
            <label for="time">活动时间</label>
            <input type="time" id="time" v-model="newAppointment.time" required>
          </div>

          <div class="form-group">
            <label for="location">活动地点</label>
            <input type="text" id="location" v-model="newAppointment.location" required placeholder="输入场地名称或地址">
          </div>

          <div class="form-group">
            <label for="locationType">场地类型</label>
            <select id="locationType" v-model="newAppointment.locationType" required>
              <option value="indoor">室内场地</option>
              <option value="outdoor">室外场地</option>
            </select>
          </div>

          <div class="form-group">
            <label for="maxPlayers">最大人数</label>
            <input type="number" id="maxPlayers" v-model="newAppointment.maxPlayers" min="2" max="20" required>
          </div>

          <div class="form-group">
            <label for="description">活动描述</label>
            <textarea id="description" v-model="newAppointment.description" placeholder="输入活动详情、水平要求等"></textarea>
          </div>

          <div class="modal-footer">
            <button type="button" class="cancel-btn" @click="closeCreateModal">取消</button>
            <button type="submit" class="confirm-btn">创建活动</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';

const store = useStore();
const router = useRouter();

// 状态管理
const createModalOpen = ref(false);
const searchKeyword = ref('');
const selectedDate = ref('all');
const selectedLocation = ref('all');
const appointments = ref([]);

// 新活动表单数据
const newAppointment = ref({
  title: '',
  date: '',
  time: '',
  location: '',
  locationType: 'indoor',
  maxPlayers: 4,
  description: ''
});

// 初始化日期为今天
onMounted(() => {
  const today = new Date().toISOString().split('T')[0];
  newAppointment.value.date = today;
  loadAppointments();
});

// 从localStorage加载约球活动
const loadAppointments = () => {
  const savedAppointments = localStorage.getItem('playingAppointments');
  if (savedAppointments) {
    appointments.value = JSON.parse(savedAppointments);
  } else {
    // 模拟初始数据
    appointments.value = [
      {
        id: 1,
        title: '周末羽毛球友谊赛',
        organizer: '羽毛球达人',
        date: '2023-10-21',
        time: '14:00-16:00',
        location: '阳光体育中心',
        locationType: 'indoor',
        maxPlayers: 8,
        currentPlayers: 6,
        description: '周末休闲局，欢迎各级水平球友参加，场地费AA',
        participants: ['羽毛球达人', '羽球小将', '运动爱好者', '球场老将', '新手玩家', '健身达人']
      },
      {
        id: 2,
        title: '新手入门练习',
        organizer: '教练小李',
        date: '2023-10-18',
        time: '19:00-21:00',
        location: '城市羽毛球馆',
        locationType: 'indoor',
        maxPlayers: 6,
        currentPlayers: 3,
        description: '针对新手的基础练习，会提供简单指导',
        participants: ['教练小李', '羽毛球新手', '初学者小明']
      },
      {
        id: 3,
        title: '户外羽毛球交流',
        organizer: '户外爱好者',
        date: '2023-10-22',
        time: '09:00-11:00',
        location: '中央公园',
        locationType: 'outdoor',
        maxPlayers: 4,
        currentPlayers: 2,
        description: '天气好的话在公园打球，自带球拍',
        participants: ['户外爱好者', '公园常客']
      }
    ];
    saveAppointments();
  }
};

// 保存约球活动到localStorage
const saveAppointments = () => {
  localStorage.setItem('playingAppointments', JSON.stringify(appointments.value));
};

// 筛选约球活动
const filteredAppointments = computed(() => {
  return appointments.value.filter(appointment => {
    // 关键词搜索
    const matchesSearch = searchKeyword.value === '' ||
      appointment.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      appointment.location.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      appointment.organizer.toLowerCase().includes(searchKeyword.value.toLowerCase());

    // 日期筛选
    const appointmentDate = new Date(appointment.date);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    const weekendStart = new Date(today);
    weekendStart.setDate(today.getDate() + (6 - today.getDay()));
    weekendStart.setHours(0, 0, 0, 0);
    const weekendEnd = new Date(weekendStart);
    weekendEnd.setDate(weekendEnd.getDate() + 1);
    const nextWeekStart = new Date(today);
    nextWeekStart.setDate(today.getDate() + 7);
    const nextWeekEnd = new Date(nextWeekStart);
    nextWeekEnd.setDate(nextWeekEnd.getDate() + 6);

    let matchesDate = true;
    if (selectedDate.value === 'today') {
      matchesDate = appointmentDate.getTime() === today.getTime();
    } else if (selectedDate.value === 'tomorrow') {
      matchesDate = appointmentDate.getTime() === tomorrow.getTime();
    } else if (selectedDate.value === 'weekend') {
      matchesDate = appointmentDate >= weekendStart && appointmentDate <= weekendEnd;
    } else if (selectedDate.value === 'nextWeek') {
      matchesDate = appointmentDate >= nextWeekStart && appointmentDate <= nextWeekEnd;
    }

    // 场地类型筛选
    const matchesLocation = selectedLocation.value === 'all' || appointment.locationType === selectedLocation.value;

    return matchesSearch && matchesDate && matchesLocation;
  });
});

// 打开创建活动模态框
const openCreateModal = () => {
  if (!store.state.isAuthenticated) {
    alert('请先登录后再创建约球活动');
    router.push('/login');
    return;
  }
  
  // 检查用户信息是否完整
  if (!store.state.user || !store.state.user.username) {
    alert('用户信息不完整，请完善个人资料');
    router.push('/profile');
    return;
  }
  createModalOpen.value = true;
};

// 关闭创建活动模态框
const closeCreateModal = () => {
  createModalOpen.value = false;
};

// 提交约球活动
const submitAppointment = () => {
  // 再次验证用户信息完整性
  if (!store.state.user || !store.state.user.username) {
    alert('用户信息不完整，请完善个人资料');
    router.push('/profile');
    return;
  }
  const newId = appointments.value.length > 0 ? Math.max(...appointments.value.map(a => a.id)) + 1 : 1;
  const newAppt = {
    id: newId,
    ...newAppointment.value,
    organizer: store.state.user.username,
    currentPlayers: 1,
    participants: [store.state.user.username]
  };

  appointments.value.push(newAppt);
  saveAppointments();

  // 重置表单
  newAppointment.value = {
    title: '',
    date: new Date().toISOString().split('T')[0],
    time: '',
    location: '',
    locationType: 'indoor',
    maxPlayers: 4,
    description: ''
  };

  closeCreateModal();
  alert('约球活动创建成功！');
};

// 加入约球活动
const joinAppointment = (appointment) => {
  if (!store.state.isAuthenticated) {
    alert('请先登录后再加入约球活动');
    router.push('/login');
    return;
  }

  // 检查用户信息是否完整
  if (!store.state.user || !store.state.user.username) {
    alert('用户信息不完整，请完善个人资料');
    router.push('/profile');
    return;
  }

  const apptIndex = appointments.value.findIndex(a => a.id === appointment.id);
  if (apptIndex === -1) return;

  // 检查是否已加入
  if (appointments.value[apptIndex].participants.includes(store.state.user.username)) {
    alert('您已加入该活动');
    return;
  }

  // 检查人数是否已满
  if (appointments.value[apptIndex].currentPlayers >= appointments.value[apptIndex].maxPlayers) {
    alert('活动人数已满');
    return;
  }

  // 加入活动
  appointments.value[apptIndex].currentPlayers++;
  appointments.value[apptIndex].participants.push(store.state.user.username);
  saveAppointments();
  alert('成功加入约球活动！');
};

// 检查是否可以加入活动
const canJoin = (appointment) => {
  if (!store.state.isAuthenticated) return false;
  if (appointment.participants.includes(store.state.user.username)) return false;
  if (appointment.currentPlayers >= appointment.maxPlayers) return false;
  return true;
};

// 获取加入按钮文本
const getJoinButtonText = (appointment) => {
  if (!store.state.isAuthenticated) return '请先登录';
  if (appointment.participants.includes(store.state.user.username)) return '已加入';
  if (appointment.currentPlayers >= appointment.maxPlayers) return '人数已满';
  return '加入活动';
};

// 获取活动状态类名
const getStatusClass = (appointment) => {
  if (appointment.currentPlayers >= appointment.maxPlayers) return 'full';
  if (appointment.currentPlayers / appointment.maxPlayers < 0.5) return 'low';
  return 'normal';
};

// 获取活动状态文本
const getStatusText = (appointment) => {
  if (appointment.currentPlayers >= appointment.maxPlayers) return '人数已满';
  if (appointment.currentPlayers / appointment.maxPlayers < 0.5) return '人数较少';
  return '人数正常';
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  });
};

// 筛选约球活动
const filterAppointments = () => {
  // 筛选逻辑已在computed属性中实现
};
</script>

<style scoped>
.playing-appointment-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.page-header {
  text-align: center;
  margin-bottom: 2.5rem;
}

.page-header h2 {
  color: #2196F3;
  margin-bottom: 0.5rem;
}

.page-header p {
  color: #666;
  margin: 0;
}

/* 创建约球按钮 */
.create-appointment-btn-container {
  text-align: right;
  margin-bottom: 1.5rem;
}

.create-appointment-btn {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
}

.plus-icon {
  font-size: 1.2rem;
}

/* 筛选区域 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.search-box {
  flex: 1;
  min-width: 200px;
}

.search-box input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
}

.filter-options {
  display: flex;
  gap: 1rem;
}

.filter-options select {
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
}

/* 约球活动列表 */
.appointments-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
}

.appointment-card {
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.appointment-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.appointment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 1.2rem 1.5rem;
  background-color: #f9f9f9;
  border-bottom: 1px solid #f0f0f0;
}

.appointment-title h3 {
  margin: 0 0 0.3rem 0;
  color: #333;
  font-size: 1.1rem;
}

.organizer {
  color: #777;
  font-size: 0.9rem;
}

.appointment-status {
  padding: 0.3rem 0.8rem;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 500;
}

.appointment-status.normal {
  background-color: #e8f5e9;
  color: #4CAF50;
}

.appointment-status.low {
  background-color: #fff3e0;
  color: #FF9800;
}

.appointment-status.full {
  background-color: #ffebee;
  color: #f44336;
}

.appointment-details {
  padding: 1.5rem;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 0.8rem;
  margin-bottom: 0.8rem;
  color: #555;
}

.icon {
  font-size: 1.2rem;
  color: #2196F3;
}

.appointment-actions {
  display: flex;
  justify-content: space-between;
  padding: 1rem 1.5rem;
  border-top: 1px solid #f0f0f0;
  background-color: #f9f9f9;
}

.join-btn {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 0.6rem 1.2rem;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.join-btn:disabled {
  background-color: #b3e5fc;
  cursor: not-allowed;
}

.share-btn {
  background: none;
  border: 1px solid #ddd;
  padding: 0.6rem 1.2rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.share-btn:hover {
  border-color: #2196F3;
  color: #2196F3;
}

.no-appointments {
  text-align: center;
  padding: 3rem;
  color: #777;
  background-color: #f9f9f9;
  border-radius: 12px;
  grid-column: 1 / -1;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s, visibility 0.3s;
  z-index: 1000;
}

.modal-overlay.active {
  opacity: 1;
  visibility: visible;
}

.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(0.9);
  width: 90%;
  max-width: 500px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0,0,0,0.2);
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s;
  z-index: 1001;
}

.modal.active {
  opacity: 1;
  visibility: visible;
  transform: translate(-50%, -50%) scale(1);
}

.modal-header {
  padding: 1.5rem;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-modal {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #777;
}

.modal-body {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1.2rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #555;
  font-weight: 500;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
}

.form-group textarea {
  min-height: 100px;
  resize: vertical;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  padding: 1.5rem;
  border-top: 1px solid #f0f0f0;
  margin-top: 1rem;
}

.cancel-btn {
  background: none;
  border: 1px solid #ddd;
  padding: 0.8rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
}

.confirm-btn {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
}

@media (max-width: 768px) {
  .appointments-list {
    grid-template-columns: 1fr;
  }
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>